<template>
  <RadModal
    width="500px"
    :visible="visible"
    :loading="loading"
    title="授权用户角色"
    @visible-change="updateVisible"
    @ok="save"
  >
    <ele-pro-table
      bordered
      ref="tableRef"
      row-key="id"
      :columns="columns"
      :init-load="false"
      :datasource="tableData"
      v-model:selection="selection"
      :toolbar="false"
      @done="loadUserOwnRole"
      height="auto"
      :need-page="false"
    />
  </RadModal>
</template>

<script setup lang="ts">
  import { ref, defineProps, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import RadModal from '@/components/RadModal/index.vue';
  import { User } from '@/api/system/user/model';
  import { grantUserRole, userOwnRoleList } from '@/api/system/user';
  import { listRoles } from '@/api/system/role';

  import {
    ColumnItem,
    EleProTableDone
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { Role } from '@/api/system/role/model';
  import { EleProTable } from 'ele-admin-pro';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: User | null;
  }>();
  const columns = ref<ColumnItem[]>([
    {
      title: '角色名称',
      dataIndex: 'name',
      showSorterTooltip: false,
      width: 120
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      showSorterTooltip: false,
      width: 110
    }
  ]);
  // 提交状态
  const loading = ref(false);

  // 表格选中数据
  const selection = ref<Role[]>([]);

  const tableData = ref<Role[]>([]);

  // 表格数据源
  const datasource = async () => {
    tableData.value = await listRoles();
    // tableRef.value?.setData();
  };

  const save = () => {
    loading.value = true;
    grantUserRole({
      userId: props.data?.id,
      orgId: props.data?.orgId,
      roleIdList: selection.value.map((x) => x.id)
    })
      .then((msg) => {
        loading.value = false;
        message.success(msg);
        updateVisible(false);
        emit('done');
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const loadUserOwnRole: EleProTableDone<Role> = ({ data }) => {
    userOwnRoleList(props.data?.id).then((res) => {
      selection.value = data.filter((x) => res?.includes(x.id));
    });
  };
  watch(
    () => props.visible,
    async (visible) => {
      if (!visible) {
        selection.value = [];
      } else {
        await datasource();
      }
    }
  );
</script>
